package com.lmaos.basetools.authority;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
 * 
 * @author lmaos
 *
 * <p>作者：张星宇</p>
 * <p>时间：2017年6月1日 下午11:31:45</p>
 * <p>说明:用户管理默认实现		</p>
 *
 */
public class UserMgImpl<UB> implements UserMg<UB>{
	AuthorityMg authorityMg = null;
	/**
	 *  默认的用户管理实现
	 */
	public UserMgImpl() {
		authorityMg = new AuthorityMgImpl();
	}
	public UserMgImpl(Collection<User<UB>> users){
		this();
		addUserCaches(users);
	}
	public UserMgImpl(AuthorityMg authorityMg) {
		this.authorityMg = authorityMg;
	}
	/**
	 * @param users 用户对象集合
	 * @param authorityMg 权限管理实现
	 */
	public UserMgImpl(Collection<User<UB>> users,AuthorityMg authorityMg) {
		this(authorityMg);
		addUserCaches(users);
	}
	
	
	protected Map<String, User<UB>> userMap = new ConcurrentHashMap<String, User<UB>>(128);
	protected Set<String> userRoleKeys = new HashSet<String>(128);
	@Override
	public AuthorityMg getAuthorityMg() {
		return authorityMg;
	}

	@Override
	public void addUserCache(User<UB> user) {
		userMap.put(user.getUsername(), user);
		userRoleKeys.add(user.getUserRoleKey());
	}

	@Override
	public void addUserCaches(Collection<User<UB>> users) {
		for (User<UB> user : users) {
			addUserCache(user);
		}
	}

	@Override
	public User<UB> getUserCache(String username) {
		
		return userMap.get(username);
	}

	@Override
	public List<User<UB>> getUsersByRoleKey(String userRoleKey) {
		List<User<UB>> users = new ArrayList<User<UB>>();
		for (Entry<String, User<UB>> user : userMap.entrySet()) {
			if(user.getKey().equals(userRoleKey)){
				users.add(user.getValue());
			}
		}
		return users;
	}

	@Override
	public Set<String> getUserRoleKeys() {
		
		return new HashSet<String>(userRoleKeys);
	}

	@Override
	public List<User<UB>> getUserCaches() {
		
		return new ArrayList<User<UB>>(userMap.values());
	}

	@Override
	public User<UB> removeUser(String username) {
		
		return userMap.remove(username);
	}

	@Override
	public List<User<UB>> removeUserByRoleKey(String userRoleKey) {
		List<User<UB>> users = getUsersByRoleKey(userRoleKey);
		for (User<UB> user : users) {
			removeUser(user.getUsername());
		}
		return users;
	}

}
